<?php
/**
 * Created by PhpStorm.
 * User: Xavier Yang
 * Date: 2018/12/25
 * Time: 14:38
 * Email:499873958@qq.com
 */
declare(strict_types=1);

namespace Xavier\Swoole\Event;


use Xavier\Exceptions\BaseException;
use Xavier\Exceptions\HttpException;
use Xavier\Facade\Container;
use Xavier\Swoole\Parse\HttpParse;
use Xavier\Swoole\Request;
use Xavier\Swoole\Response;

trait HttpEvent
{
    public function onRequest(\Swoole\Http\Server $request, \Swoole\Http\Response $response)
    {
        $this->httpRouter($request, $response);
    }

    /**
     * @param \Swoole\Http\Request $request
     * @param \Swoole\Http\Response $response
     */
    protected function httpRouter(\Swoole\Http\Request $request, \Swoole\Http\Response $response)
    {
        $req = Container::make(Request::class, $request);
        $res = Container::make(Response::class, $request, $response);
        try {
            $parse = Container::make(HttpParse::class);
            $ret   = $parse->run($req->method(), $req->uri());
            if ($ret && 200 == intval($ret['code'])) {
                $gets = $ret['get'];
                if (is_array($gets)) {
                    foreach ($gets as $key => $val) {
                        $req->setdata("get", $key, $val);
                    }
                }
                $rets = $parse->parseHandle($req->uri());
                if ($rets) {
                    $class      = $rets['class'];
                    $action     = $rets['action'];
                    $controller = Container::make($class);
                    try {
                        $controller->init($req, $res, $this->server);
                        $ret = $controller->{$action}();
                    } catch (BaseException $e) {

                    }
                    Container::release($controller);
                    unset($controller);
                    $res->end($ret);
                }
            }
        } catch (HttpException $e) {

        } catch (RouterException $e) {

        } catch (\Throwable $e) {

        }
        Container::release($req);
        Container::release($res);
        unset($req);
        unset($res);
    }
}